<template>
  <CommonPage>
    <AppCrud
      ref="tableRef"
      :columns="columns"
      default-sort="createdAt"
      v-model:query="query"
      :get-data="styleApi.page"
    >
      <query-item label="工序组">
        <a-select
          allow-clear
          class="w-full h-30"
          placeholder="请选择工序组"
          show-search
          v-model:value="query.groupId"
        >
          <a-select-option v-for="group in groups" :value="group.id">
            {{ group.name }}
          </a-select-option>
        </a-select>
      </query-item>
      <query-item label="型号">
        <a-select
          allow-clear
          show-search
          class="w-full h-30"
          placeholder="请选择型号"
          v-model:value="query.modelId"
        >
          <a-select-option v-for="model in models" :value="model.id">
            {{ model.code }} {{ model.name }}
          </a-select-option>
        </a-select>
      </query-item>

      <template #action>
        <a-button type="primary" @click="onAdd(false)">
          <template #icon><PlusOutlined></PlusOutlined></template>
          创建款式
        </a-button>
      </template>
    </AppCrud>

    <AppModal ref="modalRef" width="500px">
      <a-form ref="formRef" :model="formModel" :label-col="{ style: { width: '90px' } }">
        <a-form-item label="复制工序" v-if="copyId">
          <a-input readonly :value="copyName"></a-input>
        </a-form-item>

        <a-form-item
          label="工序组"
          name="groupId"
          :rules="[{ required: true, message: '此为必选项' }]"
        >
          <a-select placeholder="请选择工序组" v-model:value="formModel.groupId">
            <a-select-option v-for="group in groups" :value="group.id">
              {{ group.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="型号"
          name="modelId"
          :rules="[{ required: true, message: '此为必选项' }]"
        >
          <a-select placeholder="请选择型号" v-model:value="formModel.modelId">
            <a-select-option v-for="model in models" :value="model.id">
              {{ model.code }} {{ model.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="尺寸/数量">
          <table>
            <tr v-for="size in formModel.sizes">
              <td>
                <a-checkbox v-model:checked="size.check">{{ size.sizeName }}</a-checkbox>
              </td>
              <td>
                <a-input-number
                  :disabled="!size.check"
                  size="small"
                  :min="0"
                  :step="1"
                  v-model:value="size.amount"
                ></a-input-number>
              </td>
            </tr>
          </table>
        </a-form-item>

        <a-form-item label="备注">
          <a-textarea
            placeholder="请输入备注信息"
            v-model:value="formModel.description"
          ></a-textarea>
        </a-form-item>
      </a-form>
    </AppModal>
  </CommonPage>
</template>
<script setup lang="ts">
import { AppCrud, AppModal, CommonPage, QueryItem } from '@/components/common'
import { useCrud } from '@/hooks/useCrud.ts'
import styleApi, { CreateStyleDto } from '@/api/style.ts'
import { useRouter } from 'vue-router'

import { Button, Space, Tag } from 'ant-design-vue'
import sizeApi, { SizeDto } from '@/api/size.ts'
import groupApi, { GroupDto } from '@/api/group.ts'
import modelApi, { ModelDto } from '@/api/model.ts'

const router = useRouter()

const tableRef = ref()

const query = ref({
  modelId: null,
  sizeId: null,
  groupId: null,
})

const sizes = ref<SizeDto[]>([])
const models = ref<ModelDto[]>([])
const groups = ref<GroupDto[]>([])

const copyName = ref('')
const copyId = ref<string | null>(null)

const columns = [
  {
    title: '工序组',
    dataIndex: 'groupName',
    width: 150,
    render: ({ record }) => {
      return h('div', record.group.name)
    },
  },
  {
    title: '型号',
    dataIndex: 'modelName',
    width: 180,
    render: ({ record }) => {
      return h('div', record.model.code + ' ' + record.model.name)
    },
  },
  {
    title: '尺寸',
    dataIndex: 'sizeName',
    width: 300,
    render: ({ record }) => {
      return h(
        'div',
        record.sizes?.map((size) => {
          return h(Tag, {}, { default: () => size.size.name + ` (${size.amount})` })
        }),
      )
    },
  },

  {
    title: '备注信息',
    dataIndex: 'description',
    width: 150,
  },
  {
    title: '创建时间',
    width: 180,
    dataIndex: 'createdAt',
  },
  {
    title: '操作',
    align: 'center',
    width: 200,
    fixed: 'right',
    render: ({ record }: any) => {
      return h(
        Space,
        {},
        {
          default: () => [
            h(
              Button,
              {
                size: 'small',
                type: 'primary',
                danger: true,
                onClick: () => {
                  router.push({
                    name: 'Process',
                    params: {
                      id: record.id,
                    },
                  })
                },
              },
              {
                default: () => '工序管理',
              },
            ),
            h(
              Button,
              {
                size: 'small',
                onClick: () => {
                  copyId.value = record.id
                  copyName.value = record.model.code + ' ' + record.model.name
                  onAdd(true)
                },
              },
              {
                default: () => '复制',
              },
            ),
            h(
              Button,
              {
                size: 'small',
                type: 'primary',
                onClick: () => {
                  handleEdit(record)
                },
              },
              {
                default: () => '编辑',
              },
            ),
            h(
              Button,
              {
                size: 'small',
                danger: true,
                onClick: () => handleDelete(record.id),
              },
              {
                default: () => '删除',
              },
            ),
          ],
        },
      )
    },
  },
]

const {
  modalRef,
  formRef,
  formModel,
  modalAction,
  handleEdit,
  handleAdd,
  handleSave,
  handleDelete,
} = useCrud<CreateStyleDto>({
  name: '款式',
  initForm: {
    modelId: null,
    sizes: [],
    groupId: null,
    amount: 0,
    description: null,
  },
  doCreate: (form) => {
    form.sizes = form.sizes
      .filter((s) => s.check)
      .map((size) => {
        return {
          sizeId: size.sizeId,
          amount: size.amount,
        }
      })
    if (copyId.value) {
      form.copyId = copyId.value
    }
    return styleApi.create(form)
  },
  doUpdate: (id, form) => {
    form.sizes = form.sizes
      .filter((s) => s.check)
      .map((size) => {
        return {
          sizeId: size.sizeId,
          amount: size.amount,
        }
      })
    return styleApi.update(id, form)
  },
  doDelete: styleApi.delete,
  doGet: (id) => {
    return new Promise((resolve) => {
      styleApi.get(id).then(({ data }) => {
        data.sizes = data.sizes.map((s) => {
          return {
            check: !!sizes.value.find((size) => size.id == s.sizeId),
            amount: s.amount,
            sizeName: s.size.name,
            sizeId: s.sizeId,
          }
        })
        resolve({ data: data })
      })
    })
  },
  refresh: () => tableRef.value?.handleSearch(),
})

function init() {
  modelApi.all().then(({ data }) => {
    models.value = data
  })
  sizeApi.all().then(({ data }) => {
    sizes.value = data
  })
  groupApi.all().then(({ data }) => {
    groups.value = data
  })
}

function onAdd(copy: boolean = false) {
  if (!copy) {
    copyId.value = false
  }
  const s = sizes.value.map((size) => {
    return {
      sizeId: size.id,
      check: true,
      amount: 0,
      sizeName: size.name,
    }
  })
  //
  handleAdd({ sizes: s })
}

onMounted(() => {
  init()
  tableRef.value?.handleSearch()
})
</script>

<style scoped></style>
